package com.example.member.service.mp.api;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.LikeTable;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.Scanner;

/**
 * MyBatisPlus代码生成器（包路径修正版）
 */
public class MyBatisPlusGenerator {

    // 数据库配置（按需修改）
    private static final String URL = "jdbc:mysql://192.168.168.168:3306/{dataBaseName}?useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private static final String AUTHOR = "root";

    // 自动获取项目根路径
    private static final String PROJECT_ROOT = System.getProperty("user.dir");
    // 模块相对路径（根据实际结构调整）
    private static final String MODULE_PATH = "/member-service/mp/member-service-mp-api";

    public static void main(String[] args) {
        String dataBaseName = scanner("数据库名");
        String prefix = scanner("表前缀（无前缀直接回车）");

        AutoGenerator autoGenerator = new AutoGenerator(initDataSourceConfig(dataBaseName));
        autoGenerator.global(initGlobalConfig());
        autoGenerator.packageInfo(initPackageConfig());
        autoGenerator.strategy(initStrategyConfig(prefix));
        autoGenerator.execute(new VelocityTemplateEngine());
    }

    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入" + tip + ": ");
        String input = scanner.nextLine();
        if (StringUtils.isBlank(input) && !tip.contains("前缀")) {
            throw new MybatisPlusException(tip + "不能为空！");
        }
        return input.trim();
    }

    private static GlobalConfig initGlobalConfig() {
        String outputDir = PROJECT_ROOT + MODULE_PATH + "/src/main/java";

        return new GlobalConfig.Builder()
                .outputDir(outputDir)
                .author(AUTHOR)
                .disableOpenDir()
                .dateType(DateType.ONLY_DATE)
                .build();
    }

    private static DataSourceConfig initDataSourceConfig(String dataBaseName) {
        return new DataSourceConfig.Builder(
                URL.replace("{dataBaseName}", dataBaseName),
                USERNAME,
                PASSWORD
        ).dbQuery(new MySqlQuery()).build();
    }

    private static PackageConfig initPackageConfig() {
        return new PackageConfig.Builder()
                .parent("com.example.member.service.mp.api") // 关键修改点：添加api层级
                .entity("entity")
                .mapper("mapper")
                .service("service")
                .controller("controller")
                .pathInfo(Collections.singletonMap(
                        OutputFile.xml,
                        PROJECT_ROOT + MODULE_PATH + "/src/main/resources/mapper"
                ))
                .build();
    }

    private static StrategyConfig initStrategyConfig(String prefix) {
        StrategyConfig.Builder builder = new StrategyConfig.Builder();

        // 表前缀处理
        if (StringUtils.isNotBlank(prefix)) {
            builder.addTablePrefix(prefix);
        }

        // 自动扫描配置
        builder.enableSkipView()  // 跳过视图
                .disableSqlFilter() // 禁用SQL过滤
                .notLikeTable(new LikeTable("ACT_")); // 排除特定系统表

        // 实体策略
        builder.entityBuilder()
                .naming(NamingStrategy.underline_to_camel)
                .columnNaming(NamingStrategy.underline_to_camel)
                .enableLombok()
                .formatFileName("%s");

        // Mapper策略
        builder.mapperBuilder()
                .enableMapperAnnotation()
                .enableBaseResultMap()
                .formatMapperFileName("%sMapper")
                .formatXmlFileName("%sMapper");

        // Service策略
        builder.serviceBuilder()
                .formatServiceFileName("%sService")
                .formatServiceImplFileName("%sServiceImpl");

        // Controller策略
        builder.controllerBuilder()
                .enableRestStyle()
                .formatFileName("%sController");

        return builder.build();
    }
}